package com.example.mall_springboot_01.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    //私钥
    private static final String SING = "Q12@3$fas3@!";

    /**
     * 生成token
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);

        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));

        System.out.println(token);
        return token;
    }


    /**
     * 验证合法性并返回
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }

    public static void main(String[] args) {
        Map user = new HashMap<>();
        user.put("username","zhangsan");
        user.put("userid","12121");
        String token = getToken(user);
        DecodedJWT djwt = verify(token);
        System.out.println(djwt);
    }
}
